<?php

/**
 * 
 */
class Model_Mapper_Usuario extends App_Model_Mapper_Abstract {

    /**
     * 
     * @access public
     * @return void
     */
    public function save() {
        try {

            $dbUsuario = App_Model_DbTable_Factory::get('Usuario');

            parent::setValidators(array('_validIsUnique'));

            if (parent::isValid()) {

                //Criptografa senha
                $this->_data['user_senha'] = sha1($this->_data['user_senha']);

                return parent::_simpleSave($dbUsuario);
            }
        } catch (Exception $e) {

            $this->_message->addMessage($this->_config->message->error, App_Message::ERROR);
        }

        return false;
    }

    /**
     * 
     * @access public
     * @return bool
     */
    public function delete() {
        $dbUsuario = App_Model_DbTable_Factory::get('Usuario');

        $where = array('user_id = ?' => $this->_data['id']);

        $count = $dbUsuario->delete($where);

        return !empty($count);
    }

    /**
     * 
     * @access public
     * @return Zend_Db_Table_Rowset
     */
    public function fetchAll() {
        $dbUsuario = App_Model_DbTable_Factory::get('Usuario');

        $rows = $dbUsuario->fetchAll();

        return $rows;
    }

    /**
     * 
     * @access public
     * @return Zend_Db_Table_Row
     */
    public function fetchRow() {
        $dbUsuario = App_Model_DbTable_Factory::get('Usuario');

        $where = array('user_id = ?' => $this->_data['id']);

        return $dbUsuario->fetchRow($where);
    }

    /**
     * 
     * @access 	public
     * @param 	array $param
     * @return 	boolean
     */
    public function updateStatus(array $param) {
        try {

            $dbUsuario = App_Model_DbTable_Factory::get('Usuario');

            $data = array('user_status' => $param['action']);

            $where = $dbUsuario->getAdapter()->quoteInto('user_id IN(?)', $param['value']);

            $dbUsuario->update($data, $where);

            return true;
        } catch (Exception $e) {

            return false;
        }
    }

    /**
     * 
     * @access protected
     * @return bool
     */
    protected function _validIsUnique() {
        $dbUsuario = App_Model_DbTable_Factory::get('Usuario');

        $where = array();

        $where['user_email = ?'] = $this->_data['user_email'];

        if (!empty($this->_data['user_id']))
            $where['user_id <> ?'] = $this->_data['user_id'];

        $rows = $dbUsuario->fetchAll($where);

        if ($rows->count()) {
            $this->_message->addMessage('E-mail já cadastrado', App_Message::WARNING);
            return false;
        }

        return true;
    }

}